package com.example.woke;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.http.HttpMethods;
import com.woke.method.Mapupload;
import com.woke.method.MyApp;
import com.zhongcai.online.R;

import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

public class CreditActivity extends Activity implements OnClickListener {

	private CheckBox mBox;
	private EditText mTbmoney, mTpaytime, mTdays;
	private TextView mTok;
	private Intent intent;
	private int threetype;
	private TextView mTfor;
	private ProgressBar mBar;
	private TextView mTozcai;
	private MyApp myap;
	private ArrayList<String> photolist = new ArrayList<String>();
	private View layout_log;
	private WebView mWebView;
	private Dialog dialog;
	private boolean first;//�ж��������ĸ�
	private boolean isupload ;//�ж��Ƿ��ϴ��ɹ�
	private String pingtai = "";//�ж��ύƽ̨
	private int typeleixing = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_credit);

		intent = getIntent();
		threetype = intent.getIntExtra("threetype", 2);
		listurl = intent.getStringArrayListExtra("listurl");
		myap = (MyApp) getApplication();
		intview();
		getSdCardPath();
	}

	/**
	 * �ж�SDCard�Ƿ���� [��û�����SD��ʱ������ROMҲ��ʶ��Ϊ����sd��]
	 * 
	 * @return
	 */
	public static boolean isSdCardExist() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}

	/**
	 * ��ȡSD����Ŀ¼·��
	 * 
	 * @return
	 */
	public static String getSdCardPath() {
		boolean exist = isSdCardExist();
		String sdpath = "";
		if (exist) {
			sdpath = Environment.getExternalStorageDirectory()
					.getAbsolutePath();
		} else {
			sdpath = "不适用";
		}
//		Log.e("sdpath", "sdpath" + sdpath);
		return sdpath;

	}

	private void intview() {
		layout_log = getLayoutInflater().inflate(R.layout.xieyi_layout, null);
		mWebView = (WebView) layout_log.findViewById(R.id.webView1);
		findViewById(R.id.avcredit_image_back).setOnClickListener(this);
		findViewById(R.id.avcredit_red_text).setOnClickListener(this);
		mFrame = (RelativeLayout) findViewById(R.id.avcredit_frame_show);
		mTfor = (TextView) findViewById(R.id.avcredit_text_forwhy);
		mTfor.setOnClickListener(this);
		mTtype = (TextView) findViewById(R.id.avcredit_text_type);
		mTtype.setOnClickListener(this);
		mThomu = (TextView) findViewById(R.id.avcredit_text_much);
		mBox = (CheckBox) findViewById(R.id.avavcredit_check_box);
		mTbmoney = (EditText) findViewById(R.id.avcredit_text_bmoney);
		mTpaytime = (EditText) findViewById(R.id.avcredit_text_paytime);
		mTdays = (EditText) findViewById(R.id.avcredit_edit_days);
		mTok = (TextView) findViewById(R.id.avcredit_text_sendinfo);
		mTok.setOnClickListener(this);
		mTozcai = (TextView) findViewById(R.id.avcredit_text_sendzhongcai);
		mTozcai.setOnClickListener(this);
		findViewById(R.id.avcredit_relative_type).setOnClickListener(this);
		mBar = (ProgressBar) findViewById(R.id.avcredit_progress_bar);
		mBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					mTok.setBackgroundDrawable(getResources().getDrawable(
							R.drawable.rect_lightred));
					mTok.setClickable(true);
					mTozcai.setBackgroundDrawable(getResources().getDrawable(
							R.drawable.rect_lightred));
					mTozcai.setClickable(true);
				} else {
					mTok.setBackgroundDrawable(getResources().getDrawable(
							R.drawable.rect_lightgray));
					mTok.setClickable(false);
					mTozcai.setBackgroundDrawable(getResources().getDrawable(
							R.drawable.rect_lightgray));
					mTozcai.setClickable(false);
				}
			}
		});
	}

	public static File getFilePath(String filePath, String fileName) {
		File file = null;
		makeRootDirectory(filePath);
		try {
			file = new File(filePath + fileName);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return file;
	}

	public static void makeRootDirectory(String filePath) {
		File file = null;
		try {
			file = new File(filePath);
			if (!file.exists()) {
				file.mkdir();
			}
		} catch (Exception e) {

		}
	}

	private String upload(ArrayList<String> uploadFiles, float allmoney,
			String paytime, int typedd, String days, String publish) {
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		String xmString = "";  
	    String xmlUTF8=""; 
	    try {
			xmString = new String(jiekuanyontu.toString().getBytes("UTF-8"));
			xmlUTF8 = URLEncoder.encode(xmString, "UTF-8");  
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if(myap.getDatas_load ()==null){
			return String.valueOf (false);
		}
		try {
			URL url = new URL(
					HttpMethods.BASEURL+"g=api&m=quota&a=addCredit"
							+ "&quota_money=" + allmoney + "&quota_type=" + 1
							+ "&quota_use=" + xmlUTF8 + "&repay_date=" + paytime
							+ "&type=" +threetype + "&exp_date=" + days + "&publish="
							+ publish+"&user_id="+myap.getDatas_load().getId());
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			// ����POST�������������������
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			con.setRequestMethod("POST");
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			DataOutputStream ds = new DataOutputStream(con.getOutputStream());
//			Log.e("uploadFiles", "size"+uploadFiles.size());
			for (int i = 0; i < uploadFiles.size(); i++) {
				String uploadFile = uploadFiles.get(i);
				String filename = uploadFile.substring(uploadFile
						.lastIndexOf("\\") + 1);
				Log.e("filename", filename);
				ds.writeBytes(twoHyphens + boundary + end);
				// ds.writeBytes("Content-Disposition: form-data; "+"name=\"file"
				// + i + "\";filename=\""+filename + "\"" + end);
				ds.writeBytes("Content-Disposition: form-data; "+ "name=\"file" + (i + 1) + "\";filename=\""+ "zhongcai" + i + ".jpg" + "\"" + end);
				ds.writeBytes(end);
				
				Mapupload maplos = new Mapupload();
				Bitmap getimage = maplos.getimage(uploadFile,100);
				InputStream fStream = maplos.Bitmap2IS(getimage);
				if(fStream == null){
					Log.e("fStream��", "fStream");
				}else{
					Log.e("fStream��", ""+fStream);
				}
//				FileInputStream fStream = new FileInputStream(uploadFile);
				
				// FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+uploadFile);
				Log.e("已经找到数据正在发送！", "已经找到数据正在发送！");
				System.out.print("已经找到数据正在发送！");
				int bufferSize = 1024;
				byte[] buffer = new byte[bufferSize];
				int length = -1;
				while ((length = fStream.read(buffer)) != -1) {
					ds.write(buffer, 0, length);
				}
				ds.writeBytes(end);
				/* close streams */
				fStream.close();
			}
			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
			ds.flush();
			// ����BufferedReader����������ȡURL����Ӧ
			InputStream is = con.getInputStream();
			int ch;
			StringBuffer b = new StringBuffer();
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
			}
			String s = b.toString();
			Log.e("s", "s" + s);
			JSONObject json = new JSONObject(s);
			if(null != json.getString("flag") ){
				String string = json.getString("flag");
				if(string.equals("success")){
					isupload = true;
					}else{
						isupload = false;
					}		
				}
			/* ��Response��ʾ��Dialog */
//			showDialog("�ϴ��ɹ�");
			/* �ر�DataOutputStream */
			ds.close();
		} catch (Exception e) {
			System.out.print("网络出现异常！");
			Log.e("e", "e" + e);
			Log.e("e2", "e2" + e.getMessage());
			isupload = false;
			e.printStackTrace();
		}
		return ""+isupload;
	}


	/* ��ʾDialog��method */
//	private void showDialog(String mess) {
//		new AlertDialog.Builder(CreditActivity.this).setTitle("��ʾ")
//				.setMessage(mess)
//				.setNegativeButton("ȷ��", new DialogInterface.OnClickListener() {
//					public void onClick(DialogInterface dialog, int which) {
//					}
//				}).show();
//	}

	private void getdataandsend(int typedd, String publish) {
//		photolist.size()
		money_l = mTbmoney.getText().toString().trim();
		paytime_l = mTpaytime.getText().toString().trim();
		days_l = mTdays.getText().toString().trim();
		if (money_l.equals("") || money_l == null) {
			Toast.makeText(CreditActivity.this, "金额不能为空", Toast.LENGTH_SHORT).show();
		} else if (paytime_l.equals("") || paytime_l == null) {
			Toast.makeText(CreditActivity.this, "还款年限不能为空", Toast.LENGTH_SHORT).show();
		} else if (days_l.equals("") || days_l == null) {
			Toast.makeText(CreditActivity.this, "此单有效期不能为空", Toast.LENGTH_SHORT).show();
		}else if (photolist.size() <= 0) {
			Toast.makeText(CreditActivity.this, "请上传指定资料图片", Toast.LENGTH_SHORT).show();
		} else {
			int adays_l = Integer.valueOf(days_l).intValue();
			if (adays_l > 30) {
				Toast.makeText(CreditActivity.this, "有效时间不能超过30天",Toast.LENGTH_SHORT).show();
			} else {
				allmoney_l = Float.parseFloat(money_l);
					for (int i = 0; i < photolist.size(); i++) {
						String string = photolist.get(i);
						if(null == string || string.equals("")){
							photolist.remove(i);
						}
					}
					pingtai = publish;
					if(first == false){
//						mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightgray));
//						mTok.setClickable(false);
//						mBar.setVisibility(View.VISIBLE);
//						first = true;
//						ThreadTest2 threadTest2=new ThreadTest2(); 
//		                new Thread(threadTest2).start();
						
						MyTask myTask = new MyTask();
						myTask.execute("www.xinlang.com");
					}
//					upload(photolist, allmoney_l, paytime_l, typedd, days_l, publish);// ��ͼ�ϴ�
				}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == 401) {
			if (resultCode == 302) {
//				String fortype = data.getStringExtra("fortype");
				photolist = data.getStringArrayListExtra("listurl");
//				Log.e("photolist", "" + photolist);
				mThomu.setText((photolist.size())+"张图片");
			}
		}else if(requestCode == 402){
			if (resultCode == 302) {
				String fortype = data.getStringExtra("list");
				maplist = data.getStringArrayListExtra("maplist");
//				photolist = data.getStringArrayListExtra("photolist");
//				Log.e("list", "" + fortype);
				mTtype.setText(fortype);
			}
		}
	}
	
	private String money_l;
	private String paytime_l;
	private String days_l;
	private float allmoney_l;
	private TextView mTtype;
	private ArrayList<String> listurl;
	private TextView mThomu;
	private RelativeLayout mFrame;
	private String jiekuanyontu ="";
	private ArrayList<String> maplist;  
	
	
	class MyTask extends AsyncTask<String, Integer, String>{
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			mFrame.setVisibility(View.VISIBLE);
		}
		
		@Override
		protected String doInBackground(String... params) {
			//ϵͳ�������������߳�
		//	String string = params[0];
			String str = "娃哈哈";
			String upload = upload(photolist, allmoney_l, paytime_l, typeleixing, days_l, ""+pingtai);// ��ͼ�ϴ�
			return upload;
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			int in = values[0];
//			mBar.setProgress(in);
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
//			Log.e("result", result);
			if(result.equals("true")){
				Toast.makeText(CreditActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
				finish();
			}else{
				Toast.makeText(CreditActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
			}
			mFrame.setVisibility(View.GONE);
//			mTextView.setText(result);
		}
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.avcredit_image_back:
			finish();
			break;

		case R.id.avcredit_text_sendinfo:
			jiekuanyontu = mTtype.getText().toString().trim();
			
			getdataandsend(threetype, "1");// ��ͼ�ϴ�
			break;

		case R.id.avcredit_text_sendzhongcai:
			jiekuanyontu = mTtype.getText().toString().trim();
			getdataandsend(threetype, "2");
			break;

		case R.id.avcredit_red_text:
			String money = mTbmoney.getText().toString().trim();
			String day = mTpaytime.getText().toString().trim();
			ArrayList<String> list = new ArrayList<String>();
			list.add("");
			list.add(money);
			list.add(day);
			intent.setClass(CreditActivity.this,YuqiActivity.class);
			intent.putExtra("list", list);
			startActivity(intent);
			break;

		case R.id.avcredit_text_forwhy:
			intent.setClass(CreditActivity.this, BorrowforActivity.class);
			startActivityForResult(intent, 401);
			break;
			
		case R.id.avcredit_text_type:
			intent.setClass(CreditActivity.this, CreditypeActivity.class);
			startActivityForResult(intent, 402);
		break;
		
		case R.id.avcredit_relative_type:
			String trim =""+mTtype.getText().toString().trim();
			if(trim.equals("")){
				Toast.makeText(CreditActivity.this, "请选择贷款类型", Toast.LENGTH_SHORT).show();
			}else{
				intent.setClass(CreditActivity.this, CreditziliaoActivity.class);
				intent.putExtra("trim", trim);
				intent.putExtra("maplist", maplist);
				startActivityForResult(intent, 401);
			}
		break;

		default:
			break;
		}
	}
}
